﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Specialized;


using Newtonsoft.Json.Linq;
using System.Windows.Media.Media3D;
using System.Diagnostics;
using TaskManagement;

namespace CommandListPanel
{

    public class TypedJobject
    {
        public JObject Data { get; set; }
        public string Type { get; set; }
    }
    /// <summary>
    /// 原始命令列表
    /// </summary>
    public class ObservableJObjectCollection : ObservableCollection<TypedJobject>
    {
        public delegate void AddJobjectItem(TypedJobject x);
        public event AddJobjectItem addJobject;
        public delegate void RemoveJobjectItem(TypedJobject x);
        public event RemoveJobjectItem removeJobject;

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {

            base.OnCollectionChanged(e);

            // 在集合变化时执行处理代码
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                // 元素被添加
                foreach (var newItem in e.NewItems)
                {
                    TypedJobject addedItem = newItem as TypedJobject;
                    if (addedItem != null)
                    {
                        // 在这里执行添加元素时的逻辑
                        // 例如，触发事件、更新界面等

                        addJobject?.Invoke(addedItem);
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                // 元素被移除
                foreach (var oldItem in e.OldItems)
                {
                    TypedJobject removedItem = oldItem as TypedJobject;
                    if (removedItem != null)
                    {
                        // 在这里执行移除元素时的逻辑
                        // 例如，触发事件、更新界面等
                        removeJobject?.Invoke(removedItem);
                    }
                }
            }
        }
    }



    /// <summary>
    /// CommandListPanel.xaml 的交互逻辑
    /// </summary>
    public partial class CommandListPanel : UserControl
    {
        public string c1 = "#108ee9";
        public string c2 = "#77C0F4";
        public string c3 = "#4aadf4";
        /// <summary>
        /// 脚本的名称
        /// </summary>
        public string ScriptName = "";
        /// <summary>
        /// 所有被添加的CommandModel
        /// </summary>
        public List<CommandModel> CommandModelList = new List<CommandModel>();

        /// <summary>
        /// 脚本列表数据绑定器
        /// </summary>
        public CommandTypeModel ScriptDateList = new CommandTypeModel();



        /// <summary>
        /// 原始命令列表:积木块
        /// </summary>
        public ObservableJObjectCollection CommandControlList = new ObservableJObjectCollection();


        /// <summary>
        /// 被选中的积木
        /// </summary>
        public ObservableJObjectCollection CommandsUsed = new ObservableJObjectCollection();

        /// <summary>
        /// 任务管理器:开发任务.
        /// </summary>
        public static TaskManagement.TaskManager taskmanagerMan = new TaskManager();

        public double BHeight = 60;
        public  double BlockHeight = 60;

        public bool mouseoption = false;
        public JObject Cmds = new JObject();
        public CommandListPanel()
        {
            InitializeComponent();

            /*
             * 读取应用数据库
             * 应用数据库为统一的数据库
             * 数据库中包含应用的脚本,应用的配置信息:它相当于一个空的任务
             */


            /*
             * 读取任务数据库
             * 任务数据库包含了,应用的实例化状态下的脚本,以及应用的实例化状态下的配置信息.
             * 所以,应该在登录成功的时候,就要检验两个数据库存在否,如果不存在,就要创建.
             */



            testCommandListHandle();
            userControls.CollectionChanged += UserControls_CollectionChanged;// 添加集合变化事件处理程序
            this.DataContext = ScriptDateList;
            // 注册委托实例来处理右键点击事件
            CommandControlList.addJobject += ScriptCommands_addJobject;
            CommandControlList.removeJobject += ScriptCommands_removeJobject;



        }


        int commandListTop = 0;
        /// <summary>
        /// 命令列表的左边距
        /// </summary>
        public int commandListLeft = 10;
        /// <summary>
        /// 命令列表的数量
        /// </summary>
        public int commandListCount = 0;
        /// <summary>
        /// 删除一个元素时的处理
        /// </summary>
        /// <param name="x"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ScriptCommands_removeJobject(TypedJobject xx)
        {
            JObject x = xx.Data;
        }
        /// <summary>
        /// 添加一个元素时的处理
        /// </summary>
        /// <param name="x"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ScriptCommands_addJobject(TypedJobject xx)
        {
            //Console.WriteLine(x);
            JObject x = xx.Data;
            if (!x.ContainsKey("fun_type") ||!x.ContainsKey("othername"))
            {
                return;
            }
            // 创建一个新的 CommandModel 实例
            CommandModel newCommandModel = new CommandModel();
            newCommandModel.ScriptCommand = x;
            // 创建 ScaleTransform 并设置比例
            ScaleTransform scaleTransform = new ScaleTransform();
            scaleTransform.ScaleX = 0.8;
            scaleTransform.ScaleY = 0.8;

            // 应用 ScaleTransform 到 CommandModel
            newCommandModel.RenderTransform = scaleTransform;

            // 订阅 MouseDoubleClick 事件
            newCommandModel.MouseDoubleClick += CommandModel_MouseDoubleClick;
            newCommandModel.SetColors(c1, c2, c3);
            // 将新的 CommandModel 添加到 Canvas 的 Children 集合中
            commandList.Children.Add(newCommandModel);
            CommandModelList.Add(newCommandModel);
            // 如果需要设置新 CommandModel 的位置，可以使用 Canvas.SetLeft 和 Canvas.SetTop 方法
            Canvas.SetLeft(newCommandModel, commandListLeft); // 设置 X 坐标
            Canvas.SetTop(newCommandModel, 20 + (commandListCount - 1) * 56); // 设置 Y 坐标
            commandListCount++;

            //修改commandList的高度
            commandList.Height = commandListCount * 56 + 840-56;

        }


        /// <summary>
        /// 添加类型标题
        /// </summary>
        /// <param name="title"></param>
        public void ScriptCommandsAddTitle(string title)
        {

            TextBlock button = new TextBlock();
            button.Text = title;
            button.Width= 200;
            button.Height = 40;
            button.HorizontalAlignment = HorizontalAlignment.Center;
            button.VerticalAlignment = VerticalAlignment.Center;
            //字体加粗
            //文字居中
            //文字颜色#666666
            button.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#666666"));
            button.TextAlignment = TextAlignment.Center;
            button.FontWeight = FontWeights.Bold;
            button.FontSize = 18;

            // 将新的 CommandModel 添加到 Canvas 的 Children 集合中
            commandList.Children.Add(button);
            // 如果需要设置新 CommandModel 的位置，可以使用 Canvas.SetLeft 和 Canvas.SetTop 方法
            Canvas.SetLeft(button, commandListLeft); // 设置 X 坐标
            Canvas.SetTop(button, 23 + commandListCount * 56); // 设置 Y 坐标
            commandListCount++;

            //修改commandList的高度
            commandList.Height = commandListCount * 56 + 840 - 56;

        }


        public void ScrollToNewCommandModel(CommandModel commandModel)
        {
            if (commandListScrollViewer != null && commandModel != null)
            {
                // 获取 CommandModel 相对于 commandListScrollViewer 的位置
                GeneralTransform childTransform = commandModel.TransformToAncestor(commandListScrollViewer);
                Point targetPoint = childTransform.Transform(new Point(0, 0));

                // 计算应该滚动到的Y位置
                double newVerticalOffset = targetPoint.Y + commandListScrollViewer.VerticalOffset - commandListScrollViewer.Padding.Top;

                // 滚动到新的位置
                commandListScrollViewer.ScrollToVerticalOffset(newVerticalOffset);
            }
        }


        ///////////////////////////////////
        //鼠标是否按下
        bool _isMouseDown = false;
        //鼠标是否右键按下,用于判断是否弹出菜单
        bool _isMouseRightClick = false;
        //鼠标按下的位置
        Point _mouseDownPosition;
        //鼠标按下控件的位置
        Point _mouseDownControlPosition;
        //鼠标按下时控件的绝对位置
        Point _mouseDownControlPositionAbs;
        Point _monsePositionNow;
        bool mousemoveSwitch = false;
        int usercontrolListToMoveID = 0;




        /// <summary>
        /// 鼠标按下事件处理方法，用于准备移动CommandModel控件。
        /// </summary>
        /// <param name="sender">触发事件的对象，即被点击的CommandModel控件。</param>
        /// <param name="e">鼠标事件参数，包含点击按钮信息。</param>
        private void CommandModel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            // 检查是否为鼠标右键点击或已经标记为鼠标右键点击
            if (_isMouseRightClick || e.ChangedButton == MouseButton.Right)
            {
                return; // 如果是鼠标右键点击，或者已经标记为右键点击，则不进行处理
            }

            _isMouseDown = true; // 标记鼠标已按下状态

            // 获取被点击的CommandModel控件
            var commandmodel = sender as Control;
            // 获取CommandModel控件相位置起始值 
            // 标记该CommandModel正在移动中
            ((CommandModel)commandmodel).moving = true;
            spToMove = (CommandModel)commandmodel; // 设置正在移动的CommandModel

            // 置顶该CommandModel，即将其移动到Z轴最顶层
            /*
             * 1。删除原来的位置
             * 2。插入到最后位置
             */
            canvas.Children.Remove(commandmodel);
            canvas.Children.Insert(canvas.Children.Count, commandmodel);
            // 置顶
            _mouseDownPosition = e.GetPosition(this); // 记录鼠标相对于当前控件的位置
            _monsePositionNow = _mouseDownPosition;

            // 获取或创建CommandModel控件的渲染变换
            var transform = commandmodel.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                commandmodel.RenderTransform = transform;
            }

            _mouseDownControlPosition = new Point(transform.X, transform.Y); // 记录CommandModel控件的当前位置

            Window wd = Window.GetWindow(commandmodel);

            _mouseDownControlPositionAbs = commandmodel.TransformToAncestor(wd).Transform(new Point(0, 0)); // 记录CommandModel控件的绝对位置

            commandmodel.CaptureMouse(); // 捕获鼠标，以便跟踪鼠标移动事件


        }

        /// <summary>
        /// 根据成员名：name从sub中分割出新的组成员
        /// </summary>
        /// <param name="sub">组</param>
        /// <param name="name">成员名</param>
        private void GroupSplit(ref ObservableCollection<ObservableCollection<CommandModel>> sub, string name)
        {

            /*
             * 1.找到被移动的元素在总表中的位置
             * 2.分割
             * 3.重整:
             * * * 小组成员中,之下无成员的(开尾),其余的不开尾
             */
            bool checkMoveHead = false;
            int checkId = 0;
            for (int i = 0; i < sub.Count; i++)
            {
                for (int id = 0; id < sub[i].Count; id++)
                {
                    /*
                     * 1.在找到位置后,之下所有控件,先封闭,再添加到组
                     */
                    if (checkMoveHead)
                    {
                        sub[i][id].changEnableHead = false;
                        sub[i][id].changEnableShadow = false;
                        usercontrolListToMove.Add(sub[i][id]);
                        continue;
                    }
                    if (sub[i][id].Name == spToMove.Name)
                    {
                        checkId = id;//标记
                        checkMoveHead = true;
                        sub[i][id].changEnableHead = false;
                        sub[i][id].changEnableShadow = false;
                        usercontrolListToMove.Add(sub[i][id]);
                        continue;
                    }
                }
                //如果找到了就退出。
                if (checkMoveHead)
                {
                    //重整
                    //Console.WriteLine($"被移动的个数{usercontrolListToMove.Count.ToString()}...当前ID{i}确认ID{checkId}");
                    while (sub[i].Count > checkId)
                    {
                        sub[i].RemoveAt(checkId);
                    }
                    if (sub[i].Count == 0)
                    {
                        sub.RemoveAt(i);
                    }
                    else
                    {
                        GroupMask(sub[i]);//残留段整理
                        GroupMask(usercontrolListToMove);//移动段整理
                    }
                    ObservableCollection<CommandModel> ucTOMVnew = new ObservableCollection<CommandModel>();
                    for (int iii = 0; iii < usercontrolListToMove.Count; iii++)
                    {
                        ucTOMVnew.Add(usercontrolListToMove[iii]);
                    }
                    //GroupMask(ucTOMVnew);
                    sub.Add(ucTOMVnew);
                    usercontrolListToMoveID = sub.Count - 1;
                    break;
                }
            }

        }

        private void GroupMask(ObservableCollection<CommandModel> group)
        {
            /*1.先让所有组员的shadow无响应,以及头部响应为40
             * 2.再让最上的那个,头部响应为80.
             * 3.再让最下的那个,尾部有响应.
             */
            for (int gid = 0; gid < group.Count; gid++)
            {

                //group[gid].mhLimit = BlockHeight*scaleRecord11;
                group[gid].changEnableShadow = false;
            }
            if (group.Count >= 1)
            {
                //group[0].mhLimit = BlockHeight * 2*scaleRecord11;
                group[group.Count - 1].changEnableShadow = true;
            }
        }


        /// <summary>
        /// 鼠标移动，移动控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommandModel_MouseMove(object sender, MouseEventArgs e)
        {

            if (_isMouseRightClick)
            {
                return;
            }

            if (_isMouseDown)
            {

                var c = sender as Control;
                if (!mousemoveSwitch)
                {
                    /*
                     * 1.分割
                     * 2.封闭
                     */
                    mousemoveSwitch = true;
                    //Console.WriteLine("分割中。。。"+c.Name);
                    GroupSplit(ref userControls, c.Name);
                }
                var pos = e.GetPosition(this);//鼠标相对于当前控件的位置
                var dp = pos - _mouseDownPosition;
                var posAbs = GetRelativePosition(canvas, c);//鼠标相对于当前控件的绝对位置
                var movethis = pos-_monsePositionNow;//鼠标移动量
                if (
                    posAbs.X+movethis.X/ scaleRecord11 > canvas.Width-280
                    ||posAbs.X+movethis.X/ scaleRecord11 < 10
                    ||posAbs.Y+movethis.Y/ scaleRecord11 > canvas.Height-550
                    ||posAbs.Y+movethis.Y/ scaleRecord11 < -40
                    )
                {
                    return;
                }
                _monsePositionNow = pos;
                for (int i = 0; i < usercontrolListToMove.Count; i++)
                {
                    var transform1 = usercontrolListToMove[i].RenderTransform as TranslateTransform;
                    transform1.X = _mouseDownControlPosition.X + dp.X / scaleRecord11;//
                    transform1.Y = _mouseDownControlPosition.Y + dp.Y / scaleRecord11 + BHeight * i;
                }
                //var transform = c.RenderTransform as TranslateTransform;
                //transform.X = _mouseDownControlPosition.X + dp.X;
                //transform.Y = _mouseDownControlPosition.Y + dp.Y;
                /*
                 * 1。
                 */
                CommandModel cml = (CommandModel)sender;//被选中的元素
                Window window = Window.GetWindow(cml);
                Point point = cml.TransformToAncestor(window).Transform(new Point(0, 0));//被选中元素的绝对坐标
                bDdata.AbsMouse = point;

            }
        }

        private bool MouseUpCheck = false;
        /// <summary>
        /// 鼠标抬起，放置控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommandModel_MouseUp(object sender, MouseButtonEventArgs e)
        {


            if (_isMouseRightClick || !_isMouseDown)
            {
                return;
            }
            //恢复commandmodel的可接纳状态
            if (usercontrolListToMove.Count >= 1)
            {
                usercontrolListToMove[usercontrolListToMove.Count - 1].changEnableShadow = true;
            }
            for (int i = 0; i < usercontrolListToMove.Count; i++)
            {
                usercontrolListToMove[i].changEnableHead = true;
            }
            mousemoveSwitch = false;
            var c = sender as Control;

            _isMouseDown = false;
            c.ReleaseMouseCapture();


            //整理block的位置
            if (openH || openS)
            {
                MouseUpCheck = true;
                bool checkMoveHead = false;
                int mainID = 0, insertID = 0;

                for (int i = 0; i < userControls.Count; i++)
                {
                    int ucount = userControls[i].Count;
                    for (int id = 0; id < ucount; id++)
                    {
                        if (userControls[i][id].Name == spMoveTo.Name)
                        {
                            mainID = i;
                            checkMoveHead = true;
                            //从顶端顺序插入
                            if (openH)
                            {
                                //Console.WriteLine($"{spMoveTo.Name}准备插入。。。H..."+usercontrolListToMove.Count);
                                insertID = id;
                            }
                            //从底端顺序插入
                            if (openS)
                            {
                                //Console.WriteLine($"{spMoveTo.Name}准备插入。。。S..."+usercontrolListToMove.Count);

                                insertID = id + 1;
                            }
                            if (insertID > ucount - 1)
                            {
                                for (int ii = 0; ii < usercontrolListToMove.Count; ii++)
                                {
                                    userControls[i].Add(usercontrolListToMove[ii]);
                                }

                            }
                            else
                            {
                                for (int ii = 0; ii < usercontrolListToMove.Count; ii++)
                                {
                                    
                                    userControls[i].Insert(insertID, usercontrolListToMove[ii]);
                                    insertID++;
                                }

                            }
                            GroupMask(userControls[i]);
                            userControls.RemoveAt(usercontrolListToMoveID);
                            break;
                        }
                    }

                    if (checkMoveHead)
                    {
                        break;
                    }
                }




                if (openS)
                {
                    //之下的下移
                    for (int i = insertID; i < userControls[mainID].Count; i++)
                    {
                        var transform = userControls[mainID][i].RenderTransform as TranslateTransform;
                        transform.Y = transform.Y + BlockHeight * (usercontrolListToMove.Count - 1);
                    }


                    for (int i = 0; i < usercontrolListToMove.Count; i++)
                    {
                        var transform = usercontrolListToMove[i].RenderTransform as TranslateTransform;
                        var dp2 = moveto - _mouseDownControlPositionAbs;
                        transform.X = _mouseDownControlPosition.X + dp2.X / scaleRecord11;
                        transform.Y = _mouseDownControlPosition.Y + dp2.Y / scaleRecord11 + BlockHeight * (i - 1) / scaleRecord11;

                    }

                }
                if (openH)
                {

                    //之上的上移
                    for (int i = 0; i < insertID; i++)
                    {
                        var transform = userControls[mainID][i].RenderTransform as TranslateTransform;
                        transform.Y = transform.Y - BlockHeight * (usercontrolListToMove.Count - 1);
                    }



                    for (int i = 0; i < usercontrolListToMove.Count; i++)
                    {
                        var transform = usercontrolListToMove[i].RenderTransform as TranslateTransform;
                        var dp2 = moveto - _mouseDownControlPositionAbs;
                        transform.X = _mouseDownControlPosition.X + dp2.X / scaleRecord11;
                        transform.Y = _mouseDownControlPosition.Y + dp2.Y / scaleRecord11 - BlockHeight * (usercontrolListToMove.Count - i) / scaleRecord11;

                    }


                }


            }
            //清空
            bDdata.AbsMouse = new Point(0, 0);
            ((CommandModel)c).moving = false;

            usercontrolListToMove.Clear();
            spMoveTo = null;
            spToMove = null;
            //Console.WriteLine("当前分组数量..." + userControls.Count);
            for (int i = 0; i < userControls.Count; i++)
            {
                Console.WriteLine(userControls[i].Count);
                
            }

        }

        /// <summary>
        /// 根据控件名称，找到控件所在的组List<CommandModel>,以及它的index
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private ObservableCollection<CommandModel> selectGroup(string name)
        {

            for (int i = 0; i < userControls.Count; i++)
            {
                for (int ii = 0; ii < userControls[i].Count; ii++)
                {
                    if (userControls[i][ii].Name == name)
                    {
                        return userControls[i];
                    }
                }
            }
            return null;
        }
        int MyProperty = 0;



        /// <summary>
        /// 接收方控件
        /// </summary>
        public CommandModel spMoveTo = null;
        /// <summary>
        /// 被移动的控件
        /// </summary>
        public CommandModel spToMove = null;
        /// <summary>
        /// 所有控件都在这里
        /// </summary>
        //public ObservableCollection<ObservableCollection<CommandModel>> UserControList=new ObservableCollection<ObservableCollection<CommandModel>>();
        /// <summary>
        /// 所有控件都在这里
        /// </summary>
        public ObservableCollection<ObservableCollection<CommandModel>> userControls = new ObservableCollection<ObservableCollection<CommandModel>>();
        /// <summary>
        /// 马上要被移动的控件
        /// </summary>
        ObservableCollection<CommandModel> usercontrolListToMove = new ObservableCollection<CommandModel>();

        /// <summary>
        /// 分组变化的事件处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControls_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Console.WriteLine("小组集合变化..................");
            testCommandListHandle();
            // 在这里处理外部集合的变化事件
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                Console.WriteLine("小组集合变化..................添加小组,组员数量"+e.NewItems.Count);

                // 处理外部集合的添加操作
                foreach (var newItem in e.NewItems)
                {
                    var innerCollection = newItem as ObservableCollection<CommandModel>;
                    if (innerCollection != null)
                    {
                        // 添加内部集合的事件处理程序
                        innerCollection.CollectionChanged += InnerList_CollectionChanged;
                        
                    }
                }
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                Console.WriteLine("小组集合变化..................删除小组");

                // 处理外部集合的移除操作
            }
            // 其他操作
        }
        /// <summary>
        /// 内部集合成员变化的事件处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InnerList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {

            //Console.WriteLine("内部集合变化..................");
            testCommandListHandle();
            // 在这里处理内部集合的变化事件
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                Console.WriteLine("内部集合变化..................添加命令");
                //添加的数据
                var test= e.NewItems[0] as CommandModel;
                Console.WriteLine(test.ScriptCommand);


                // 处理内部集合的添加操作
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                Console.WriteLine("内部集合变化..................删除命令");
                // 处理内部集合的移除操作
            }
            else
            {
                Console.WriteLine("内部集合变化..................修改命令");

            }
            // 其他操作
        }

        /// <summary>
        /// 开发任务管理器
        /// </summary>
        private void testCommandListHandle()
        {
            //DevelopMission.CommandList
            //Console.WriteLine("处理开发任务数据的变动");
        }


        CommandModel MouseSelectedCommand = null; // 用于跟踪当前选中的CommandModel

        /// <summary>
        /// 双击事件处理方法，用于创建新的积木块（CommandModel）。
        /// </summary>
        /// <param name="sender">触发事件的对象，即被双击的CommandModel控件。</param>
        /// <param name="e">鼠标事件参数，包含双击事件信息。</param>
        private void CommandModel_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            CommandModel commandModel = sender as CommandModel;
            // 创建一个新的CommandModel控件
            CommandModel rtb2 = new CommandModel();
            rtb2.BlockOutline.Fill=commandModel.BlockOutline.Fill;
            rtb2.BlockIndexBlank.Fill = commandModel.BlockIndexBlank.Fill;
            rtb2.BlankDockPanel.Background= commandModel.BlankDockPanel.Background;

            rtb2.ScriptCommand = commandModel.ScriptCommand;
            #region 把新建的控件添加到数组里去
            ObservableCollection<CommandModel> ct = new ObservableCollection<CommandModel>();
            ct.CollectionChanged += InnerList_CollectionChanged;
            ct.Add(rtb2);
            userControls.Add(ct);
            #endregion

            // 调整缩放比例
            ScaleTransform scaleTransform = new ScaleTransform();
            scaleTransform.ScaleX = 1;
            scaleTransform.ScaleY = 1;
            rtb2.RenderTransform = scaleTransform;

            rtb2.Name = "mypr" + MyProperty; // 为新的CommandModel设置一个唯一的名称
            canvas.Children.Add(rtb2); // 将新的CommandModel添加到Canvas中
            rtb2.Margin = new Thickness(100, 100, 0, 0); // 设置新CommandModel的位置
            rtb2.MyProperty = MyProperty++;

            rtb2.idNum = MyProperty;
            rtb2.indexNumber.Text = MyProperty.ToString();

            rtb2.Name = "dr" + MyProperty;
            rtb2.MouseDown += CommandModel_MouseDown; // 添加MouseDown事件处理程序
            rtb2.MouseMove += CommandModel_MouseMove; // 添加MouseMove事件处理程序
            rtb2.MouseUp += CommandModel_MouseUp; // 添加MouseUp事件处理程序
            rtb2.SetBinding(CommandModel.AbsMouseProperty, new Binding()
            {
                Source = bDdata,
                Path = new PropertyPath("AbsMouse")
            });

            rtb2.cmdHead.IsVisibleChanged += openMouthHead; // 添加IsVisibleChanged事件处理程序
            rtb2.cmdShadow.IsVisibleChanged += openMouthShadow; // 添加IsVisibleChanged事件处理程序
            rtb2.arrangeDis += new CommandModel.ARRange(delegate ()
            {
                Console.WriteLine("阴影已消失，准备重整理.......................");
            });
            rtb2.arrangeHead += new CommandModel.ARRange(delegate ()
            {
                Console.WriteLine(">>>>>>>>>>头部已出现，准备重整理.......................");
            });
            rtb2.arrangeShadow += new CommandModel.ARRange(delegate ()
            {
                Console.WriteLine(">>>>>>>>>>阴影已出现，准备重整理.......................");
            });

            // 鼠标选中此积木块的时候，修改颜色
            MouseButtonEventHandler rtb2MouseDown = (e1, o1) =>
            {
                if (MouseSelectedCommand != null)
                {
                    // 取消之前选中CommandModel的红色边框
                    MouseSelectedCommand.BlockOutline.Stroke = Brushes.AliceBlue;
                }
                rtb2.BlockOutline.Stroke = Brushes.OrangeRed; // 为当前选中的CommandModel添加红色边框
                MouseSelectedCommand = rtb2; // 更新选中的CommandModel

                // 如果是鼠标右键点击，就弹出菜单
                if (o1.RightButton == MouseButtonState.Pressed)
                {
                    Console.WriteLine("右键点击");
                    _isMouseRightClick = true;

                    // 弹出菜单
                    ContextMenu contextmenu = new ContextMenu();
                    MenuItem miRun= new MenuItem();
                    miRun.Header = "运行";
                    //文字颜色
                    //#666666
                    miRun.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#108ee9"));
                    miRun.Click += (e2, o2) =>
                    {
                        
                        scriptSave_Click(null,null);//先保存再单元测试

                        // 运行CommandModel控件
                        Console.WriteLine("运行\n"+rtb2.ScriptCommand);
                        taskmanagerMan.FindCommandExcute(rtb2.ScriptCommand);
                        //CommandModel.MaskWork = true;
                        //CommandModel.MaskWork = false;
                    };
                    contextmenu.Items.Add(miRun);

                    MenuItem miCopy = new MenuItem();
                    miCopy.Header = "复制";
                    miCopy.Click += (e2, o2) =>
                    {
                        // 复制CommandModel控件
                        Console.WriteLine("复制");
                        //CommandModel.MaskWork = true;
                        //CommandModel.MaskWork = false;
                    };
                    contextmenu.Items.Add(miCopy);

                    MenuItem miCut = new MenuItem();
                    miCut.Header = "剪切";
                    miCut.Click += (e2, o2) =>
                    {
                        // 剪切CommandModel控件
                        Console.WriteLine("剪切");
                        //CommandModel.MaskWork = true;
                        //CommandModel.MaskWork = false;
                    };
                    contextmenu.Items.Add(miCut);

                    MenuItem miPaste = new MenuItem();
                    miPaste.Header = "粘贴";
                    miPaste.Click += (e2, o2) =>
                    {
                        // 粘贴CommandModel控件
                        Console.WriteLine("粘贴");
                        //CommandModel.MaskWork = true;
                        //CommandModel.MaskWork = false;
                    };
                    contextmenu.Items.Add(miPaste);


                    MenuItem miDelete = new MenuItem();
                    miDelete.Header = "删除";
                    miDelete.Click += (e2, o2) =>
                    {
                        // 删除CommandModel控件
                        Console.WriteLine("删除");
                        canvas.Children.Remove(rtb2);

                        // 从数组中删除CommandModel
                        for (int i = 0; i < userControls.Count; i++)
                        {
                            for (int ii = 0; ii < userControls[i].Count; ii++)
                            {
                                if (userControls[i][ii].Name == rtb2.Name)
                                {
                                    userControls[i].RemoveAt(ii);
                                    if (userControls[i].Count == 0)
                                    {
                                        userControls.RemoveAt(i);
                                    }
                                    break;
                                }
                            }

                        }
                    };
                    contextmenu.Items.Add(miDelete);
                    
                    
                    contextmenu.IsOpen = true;
                    contextmenu.Closed += (e3, o3) =>
                    {
                        _isMouseRightClick = false;
                    };
                }
            };

            // 为新加的控件添加MouseDown事件处理程序
            rtb2.MouseDown += rtb2MouseDown;

            // 给新加的控件添加transform
            var transform = rtb2.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                rtb2.RenderTransform = transform;
            }
        }



        bool openH = false;
        bool openS = false;
        Point moveto = new Point(0, 0);
        private void openMouthHead(object sender, DependencyPropertyChangedEventArgs e)
        {
            Canvas head = (Canvas)sender;
            if (head.IsVisible && !openH)
            {
                spMoveTo = (CommandModel)((Grid)((StackPanel)head.Parent).Parent).Parent;
                Window window = Window.GetWindow(head);
                Point point = head.TransformToAncestor(window).Transform(new Point(0, 0));
                openH = true;
                moveto = point;
                openArms(spMoveTo.Name, true, BlockHeight);
                return;
            }
            else
            {
                openH = false;
                if (MouseUpCheck)
                {
                    MouseUpCheck = false;
                    return;
                }
                else
                {
                    //CommandModel.MaskWork = true;
                    openArms(spMoveTo.Name, true, -BlockHeight);
                    //CommandModel.MaskWork = false;
                }
            }
        }



        private void openMouthShadow(object sender, DependencyPropertyChangedEventArgs e)
        {
            Canvas shadow = (Canvas)sender;
            if (shadow.IsVisible && !openS)
            {
                spMoveTo = (CommandModel)((Grid)((StackPanel)shadow.Parent).Parent).Parent;
                Window window = Window.GetWindow(shadow);
                Point point = shadow.TransformToAncestor(window).Transform(new Point(0, 0));
                openS = true;
                moveto = point;
                openArms(spMoveTo.Name, false, BlockHeight);
                return;
            }
            else
            {
                openS = false;
                if (MouseUpCheck)
                {
                    MouseUpCheck = false;
                    return;
                }
                else
                {
                    //CommandModel.MaskWork= true;
                    openArms(spMoveTo.Name, false, -BlockHeight);
                    //CommandModel.MaskWork = false;
                }
            }
        }

        /// <summary>
        /// 调整控件组位置
        /// </summary>
        /// <param name="name">目标控件名称</param>
        /// <param name="UD"></param>
        /// <param name="ht"></param>
        private void openArms(string name, bool UD, double ht)
        {

            Console.WriteLine($"openArms:{name}...{UD}...{ht}");

            if (CommandModel.MaskWork != 0)
            {
                return;
            }
            //如果被占用，就等待
            //等待完，就马上占用
            CommandModel.MaskWork++;
            if (CommandModel.MaskWork > 1)
            {
                return;
            }
            for (int i = 0; i < userControls.Count; i++)
            {
                for (int ii = 0; ii < userControls[i].Count; ii++)
                {
                    if (userControls[i][ii].Name == name)
                    {

                        //开始调整位置
                        ////整体上移
                        if (UD)
                        {
                            for (int iii = 0; iii < ii; iii++)
                            {

                                var transform = userControls[i][iii].RenderTransform as TranslateTransform;
                                if (transform == null)
                                {
                                    transform = new TranslateTransform();
                                    userControls[i][iii].RenderTransform = transform;
                                }
                                transform.X = transform.X;
                                transform.Y = transform.Y - ht;
                            }
                        }
                        ////整体下移
                        if (!UD)
                        {
                            for (int iii = ii + 1; iii < userControls[i].Count; iii++)
                            {
                                var transform = userControls[i][iii].RenderTransform as TranslateTransform;
                                if (transform == null)
                                {
                                    transform = new TranslateTransform();
                                    userControls[i][iii].RenderTransform = transform;
                                }
                                transform.X = transform.X;
                                transform.Y = transform.Y + ht;

                            }
                        }
                        CommandModel.MaskWork = 0;
                        return;
                    }
                }
            }
            CommandModel.MaskWork = 0;
        }


        public BDdata bDdata = new BDdata();
        public class BDdata : INotifyPropertyChanged
        {

            private Point absmouse;
            public Point AbsMouse
            {
                get { return absmouse; }
                set
                {
                    absmouse = value;
                    if (PropertyChanged != null)
                    {
                        ExcInvoke("AbsMouse");
                    }
                }
            }



            public event PropertyChangedEventHandler PropertyChanged;
            private void ExcInvoke(string propertyName)
            {

                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));

            }

        }








        double scaleRecord11 = 1.0;
        /// <summary>
        /// 鼠标滚轮缩放:已弃用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            var canvas = sender as Canvas;

            //var scale = (e.Delta > 0) ? 1.1 : (1.0 / 1.1); // 这里可以调整缩放比例

            if (e.Delta > 0)
            {
                scaleRecord11 += 0.05;

                if (scaleRecord11 >= 1.0)
                {
                    scaleRecord11 = 1.0;
                    //return;
                }
            }
            else
            {
                scaleRecord11 -= 0.05;

                if (scaleRecord11 <= 0.1)
                {
                    scaleRecord11 = 0.1;
                    //return;
                }
            }
            ScaleTransformAll(scaleRecord11);//通知所有积木块实例,缩放比例并处理
            BlockHeight = BHeight * scaleRecord11;
            canvas.LayoutTransform = new ScaleTransform(scaleRecord11, scaleRecord11);

            //canvas的上下左右边界的位置不能超过scrollviewer的上下左右

            Point point = GetRelativePosition(scrollviewer, canvas);


            /*判断：
             * 1。当前，canvas的高宽，是否超过scrollviewer的高宽
             * 2。
             */
            var transform = canvas.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                canvas.RenderTransform = transform;
            }

            if (scrollviewer.Width > point.X + canvas.Width * scaleRecord11)
            {
                //Console.WriteLine("右边界超出" + (point.X + canvas.Width * scaleRecord11 - scrollviewer.Width));
                //把canvas的位置向右移动100

                transform.X = transform.X - (point.X + canvas.Width * scaleRecord11 - scrollviewer.Width);

            }
            if (scrollviewer.Height > point.Y + canvas.Height * scaleRecord11)
            {
                //Console.WriteLine("下边界超出");
                //把canvas的位置向下移动100
                transform.Y = transform.Y - (point.Y + canvas.Height * scaleRecord11 - scrollviewer.Height);

            }

            //Console.WriteLine($"canvas的高宽:{canvas.Width * scaleRecord11}...{canvas.Height * scaleRecord11}");
            //Console.WriteLine($"canvas的位置:{point.X}...{point.Y}");

            // 防止事件进一步传播
            e.Handled = true;

        }

        public static Point GetRelativePosition(FrameworkElement parent, FrameworkElement child)
        {
            // 使用 TransformToAncestor 获取子控件相对于父控件的转换信息
            GeneralTransform childTransform = child.TransformToAncestor(parent);
            // 获取子控件的左上角相对于父控件的位置
            Point relativePoint = childTransform.Transform(new Point(0, 0));
            return relativePoint;
        }
        //创建一个函数,用于通知所有积木块实例,缩放比例并处理
        /// <summary>
        /// 通知所有积木块实例,缩放比例并处理
        /// </summary>
        /// <param name="scale"></param>
        public void ScaleTransformAll(double scale)
        {
            foreach (ObservableCollection<CommandModel> item in userControls)
            {
                foreach (CommandModel item1 in item)
                {
                    item1.ScaleMask(scaleRecord11);
                }
            }
        }


        bool _isMouseDown11 = false;
        //鼠标是否右键按下,用于判断是否弹出菜单
        bool _isMouseRightClick11 = false;
        //鼠标按下的位置
        Point _mouseDownPosition11;
        //鼠标按下控件的位置
        Point _mouseDownControlPosition11;

        private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            if (_isMouseRightClick)
            {
                return;
            }

            _isMouseDown11 = true;
            //////////////////////////////////////////////
            var c = sender as Canvas;
            _mouseDownPosition11 = e.GetPosition(this);
            var transform = c.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                c.RenderTransform = transform;
            }
            _mouseDownControlPosition11 = new Point(transform.X, transform.Y);
            c.CaptureMouse();
        }
        /// <summary>
        /// 鼠标移动，移动控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isMouseRightClick)
            {
                return;
            }

            if (_isMouseRightClick11 || !_isMouseDown11)
            {
                return;
            }

            var c = sender as Canvas;
            var pos = e.GetPosition(this);
            var dp = pos - _mouseDownPosition11;
            var transform = c.RenderTransform as TranslateTransform;

            double scaledWidth = c.Width * scaleRecord11;
            double scaledHeight = c.Height * scaleRecord11;

            // 计算新的平移值
            double newX = _mouseDownControlPosition11.X + dp.X;
            double newY = _mouseDownControlPosition11.Y + dp.Y;

            // 限制移动范围以防止超出边界
            if (newX > 0) newX = 0;
            if (newY > 0) newY = 0;
            if (newX < -(scaledWidth - scrollviewer.ActualWidth)) newX = -(scaledWidth - scrollviewer.ActualWidth);
            if (newY < -(scaledHeight - scrollviewer.ActualHeight)) newY = -(scaledHeight - scrollviewer.ActualHeight);

            transform.X = newX;
            transform.Y = newY;
        }

        /// <summary>
        /// 鼠标抬起，放置控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_isMouseRightClick)
            {
                return;
            }

            var c = sender as Canvas;
            _isMouseDown11 = false;
            c.ReleaseMouseCapture();
        }

        private void arrangeButton_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine(userControls.Count > 1 && userControls[0].Count>1 ?userControls[0][0].ScriptCommand:null);
            //x方向上按 280间距排列
            //y方向上自动排列
            double actualWidth = 270;
            double actualHeight = BHeight;
            double startX = 20,startY=-25;
            int countX=0, countY = 0;
            for (int i = 0; i < userControls.Count; i++)
            {
                startX=20+actualWidth*countX;
                countY = 0;
                for (int j = 0; j < userControls[i].Count; j++)
                {
                    startY = -25 + actualHeight * countY;
                    Point point = GetRelativePosition(canvas, userControls[i][j]);
                    MoveControl(userControls[i][j], startX-point.X, startY - point.Y);
                    countY += 1;
                }
                countX+=1;
            }
        }

        public static void MoveControl(FrameworkElement control, double deltaX, double deltaY)
        {
            // 获取或创建控件的 TranslateTransform
            TranslateTransform transform = control.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                // 如果控件还没有 TranslateTransform，创建一个新的实例
                transform = new TranslateTransform();
                control.RenderTransform = transform;
            }

            // 更新控件的位置
            transform.X += deltaX;
            transform.Y += deltaY;
        }

        /// <summary>
        /// 当命令类型被选中,滚到它的位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScriptListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取ListBox
            var listBox = sender as ListBox;
            if (listBox != null && listBox.SelectedItem != null)
            {
                // 获取选中的item绑定的数据
                var selectedData = listBox.SelectedItem as CommandType;  // 替换YourDataType为实际的数据类型

                // 输出数据
                if (selectedData != null)
                {
                    ScrollToNewCommandModel(selectedData.Commandmodel);
                    Console.WriteLine(selectedData.Commandmodel.Name);  // 或其他您想要的输出方式
                                                      // 如果YourDataType是一个复杂类型，您可能需要访问特定的属性来输出，例如: Console.WriteLine(selectedData.Name);
                }
            }
        }

        private void scriptSave_Click(object sender, RoutedEventArgs e)
        {
            //保存脚本
            //先整理一下
            arrageCommandList();

        }
        private void scriptRun_Click(object sender, RoutedEventArgs e)
        {
            //先整理一下
            arrageCommandList();
        }

        private void scriptTitleEditButton_Click(object sender, RoutedEventArgs e)
        {
            if (scriptTitleBlock.Visibility==Visibility.Visible)
            {
                scriptTitleBlock.Visibility = Visibility.Hidden;
                scriptTitleTbox.Visibility = Visibility.Visible;
                scriptTitleEditButton.Content = "✔️";
            }
            else
            {
                
                scriptTitleBlock.Visibility = Visibility.Visible;
                scriptTitleBlock.Text = scriptTitleTbox.Text;
                scriptTitleTbox.Visibility = Visibility.Hidden;
                
                scriptTitleEditButton.Content = "✏️";
            }
        }




        private void arrageCommandList()
        {
            taskmanagerMan.ScriptCommandList.Clear();
            if (userControls.Count >= 1)
            {
                for (int i = 0; i < userControls[0].Count; i++)
                {
                    taskmanagerMan.ScriptCommandList.Add(userControls[0][i].ScriptCommand);
                }
            }


            for (int i = 0; i < taskmanagerMan.ScriptCommandList.Count; i++)
            {
                Console.WriteLine(taskmanagerMan.ScriptCommandList[i]);

            }

        }
    }







    public class CommandType : INotifyPropertyChanged
    {
        /// <summary>
        /// 脚本的名称
        /// </summary>
        public string _name;
        /// <summary>
        /// 脚本的类型
        /// </summary>
        public CommandModel _commandmodel;
        private SolidColorBrush _backgroundColor;


        /// <summary>
        /// 脚本的名称
        /// </summary>
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
        /// <summary>
        /// 脚本的类型
        /// </summary>
        public CommandModel Commandmodel
        {
            get { return _commandmodel; }
            set
            {
                _commandmodel = value;
                OnPropertyChanged(nameof(Commandmodel));
            }
        }
        // 背景颜色属性
        public SolidColorBrush BackgroundColor
        {
            get { return _backgroundColor; }
            set
            {
                if (_backgroundColor != value)
                {
                    _backgroundColor = value;
                    OnPropertyChanged(nameof(BackgroundColor));
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }


    public class CommandTypeModel : INotifyPropertyChanged
    {
        private ObservableCollection<CommandType> _scriptList;
        private CommandType _selectedScript;

        public ObservableCollection<CommandType> ScriptList
        {
            get { return _scriptList; }
            set
            {
                _scriptList = value;
                OnPropertyChanged(nameof(ScriptList));
            }
        }
        public CommandType SelectedScript
        {
            get { return _selectedScript; }
            set
            {
                _selectedScript = value;
                OnPropertyChanged(nameof(SelectedScript));
            }
        }

        public CommandTypeModel()
        {
            // 初始化 ScriptList 和其他数据
            ScriptList = new ObservableCollection<CommandType>();
            int i = 0;
            ScriptList.CollectionChanged += (sender, e) =>
            {
                //如果是添加操作

                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {

                    //遍历添加的项
                    foreach (CommandType item in e.NewItems)
                    {
                        //添加事件处理

                        //获取数据绑定的对象

                        i++;
                    }
                }
            };
            //// 添加示例数据
            //ScriptList.Add(new ScriptItem { Name = "Script1", Version = "1.0" });
            //ScriptList.Add(new ScriptItem { Name = "Script2", Version = "2.0" });
            //// 其他初始化操作
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}
